using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using BaseAmd.Mmp;
using BaseAmd.Mmp.FileNameFormat;
using HslCommunication;
using Catastrophe.AutoSulution.TaskM;
using Catastrophe.Common.FileM;
using Tamir.SharpSsh;

namespace SiemensAmd.Mmp
{
	public class SieCncScp : ISieCncScp, IProgHandler
	{
		private Scp _scpClient;

		public string Ip { get; set; } = "";


		public string StationName { get; set; } = "";


		public string User { get; set; } = "";


		public string Pwd { get; set; } = "";


		public bool IsNameFormat { get; set; }

		public int ConTimeOut { get; set; } = 5000;


		public Action<int, int, FileInfoEntity> DownLoadNcProcessHandler { get; set; }

		public Action<int, int> UploadPcProcessHandler { get; set; }

		public bool IsConnect => this._scpClient?.Connected ?? false;

		public FileTransferEvent TransferProgressBar { get; set; }

		public FileTransferEvent TransferEnd { get; set; }

		public Action<TransResult> TransErrorHandler { get; set; }

		public SieCncScp(ProgApiResources sshApiRes)
		{
			SshApiResources sshApiResources = sshApiRes as SshApiResources;
			if (sshApiResources != null)
			{
				this.Ip = sshApiResources.IpAdr;
				this.User = sshApiResources.UserName;
				this.Pwd = sshApiResources.Pwd;
				return;
			}
			throw new Exception("初始化失败资源对象类型非MmpApiResoures");
		}

		public SieCncScp(string ip, string user = "manufact", string pwd = "SUNRISE")
		{
			this.Ip = ip;
			this.User = user;
			this.Pwd = pwd;
		}

		public BaseFileRename FileRename()
		{
			return new FileRenameSsh();
		}

		public TransResult UploadPcSingle(FileInfoEntity remoteFileInfo, string localPath, ProgApiResources apiRes)
		{
			string fromFilePath = Path.Combine(remoteFileInfo.Path, remoteFileInfo.FormatName);
			TransResult transResult = new TransResult
			{
				Message = "",
				IsSuccess = true
			};
			try
			{
				transResult = this.Connect();
				this._scpClient.Get(fromFilePath, localPath);
				this.Disconnect();
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.OprType = "回传";
				transResult.TimeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
				transResult.Message = "回传失败：" + ex;
				this.TransErrorHandler?.Invoke(transResult);
			}
			return transResult;
		}

		public TransResult DownLoadNcSingle(FileInfoEntity localFile, FileInfoEntity remoteFile, ProgApiResources apiRes)
		{
			SshApiResources sshApiResources = (SshApiResources)apiRes;
			TransResult transResult = new TransResult
			{
				Message = "",
				IsSuccess = true
			};
			try
			{
				transResult = this.Connect();
				this._scpClient.Recursive = sshApiResources.Recursive;
				this._scpClient.Put(localFile.FullName, remoteFile.Path + remoteFile.FormatName);
				this.Disconnect();
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.OprType = "下载";
				transResult.TimeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
				transResult.Message = "下载失败:" + ex;
				this.TransErrorHandler?.Invoke(transResult);
			}
			return transResult;
		}

		public TransResult DownLoadNcMulti(List<FileInfoEntity> entityBuf, string remotePath, ProgApiResources apiRes)
		{
			SshApiResources sshApiResources = (SshApiResources)apiRes;
			TransResult transResult = new TransResult
			{
				Message = "",
				IsSuccess = true
			};
			try
			{
				transResult = this.Connect();
				foreach (FileInfoEntity item in entityBuf)
				{
					this._scpClient.Recursive = sshApiResources.Recursive;
					this._scpClient.Put(item.FullName, remotePath + item.FormatName);
				}
				this.Disconnect();
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.OprType = "下载";
				transResult.TimeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
				transResult.Message = "下载失败:" + ex;
				this.TransErrorHandler?.Invoke(transResult);
			}
			return transResult;
		}

		public TransResult Rename(string srcName, string destName, string root, ProgApiResources apiRes)
		{
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(4, 4);
			defaultInterpolatedStringHandler.AppendLiteral("mv ");
			defaultInterpolatedStringHandler.AppendFormatted(root);
			defaultInterpolatedStringHandler.AppendFormatted(srcName);
			defaultInterpolatedStringHandler.AppendLiteral(" ");
			defaultInterpolatedStringHandler.AppendFormatted(root);
			defaultInterpolatedStringHandler.AppendFormatted(destName);
			string text = defaultInterpolatedStringHandler.ToStringAndClear();
			return this.RunCommand(new string[1] { text });
		}

		public TransResult DeleteFile(List<string> fileAry, ProgApiResources apiRes)
		{
			TransResult transResult = this.RunCommand(new string[1] { CommandHelp.DeleteMultipleCmd(fileAry.ToArray()) });
			transResult.IsSuccess = transResult.Message.TrimEnd() == "";
			if (transResult.Content.TrimEnd() == "-1")
			{
				transResult.IsSuccess = false;
				transResult.Message = "文件不存在！";
			}
			return transResult;
		}

		public Tuple<TransResult, List<FileInfoEntity>> GetProgDetails(string stationName, ProgApiResources apiRes)
		{
			SshApiResources sshApiResources = (SshApiResources)apiRes;
			TransResult transResult = this.RunCommand(new string[1] { " ls -l " + sshApiResources.RemoteRootPath + " " });
			List<FileInfoEntity> list = new List<FileInfoEntity>();
			int num = 2;
			int queryParentNodeId = -1;
			if (transResult.IsSuccess)
			{
				FileInfoEntity fileInfoEntity = new FileInfoEntity
				{
					IsDirectory = true,
					Path = sshApiResources.RemoteRootPath,
					Name = sshApiResources.RemoteRootPath,
					Type = FilePathTypeEnum.Dir,
					QueryParentNodeId = queryParentNodeId,
					QueryNodeId = num
				};
				list.Add(fileInfoEntity);
				string content = transResult.Content;
				string[] array = content.Split('\n');
				string[] array2 = array;
				foreach (string text in array2)
				{
					num++;
					List<string> list2 = (from x in text.Split(' ')
						where x.Trim() != ""
						select x).ToList();
					if (list2.Count == 9 && !(list2.Last().Split('_').Last() != "MPF"))
					{
						FileInfoEntity fileEntity = new FileInfoEntity
						{
							QueryNodeId = num,
							QueryParentNodeId = fileInfoEntity.QueryNodeId,
							FormatName = list2.Last(),
							Type = FilePathTypeEnum.File
						};
						fileEntity.FullName = sshApiResources.RemoteRootPath + fileEntity.FormatName;
						Tuple<bool, string, string> tuple = this.FileRename().NameFormatReverse(fileEntity.FormatName);
						fileEntity.Path = sshApiResources.RemoteRootPath;
						fileEntity.Extension = tuple.Item3;
						fileEntity.ExtensionWithoutPoint = (tuple.Item3.StartsWith(".") ? tuple.Item3.Remove(0, 1) : fileEntity.Extension);
						fileEntity.Name = tuple.Item2;
						fileEntity.Path = sshApiResources.RemoteRootPath;
						if (!list.Any((FileInfoEntity x) => x.FormatName == fileEntity.FormatName))
						{
							FileInfoEntity fileInfoEntity2 = fileEntity;
							DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(2, 3);
							defaultInterpolatedStringHandler.AppendFormatted(list2[5]);
							defaultInterpolatedStringHandler.AppendLiteral("/");
							defaultInterpolatedStringHandler.AppendFormatted(list2[6]);
							defaultInterpolatedStringHandler.AppendLiteral(" ");
							defaultInterpolatedStringHandler.AppendFormatted(list2[7]);
							fileInfoEntity2.ModifyTime = defaultInterpolatedStringHandler.ToStringAndClear();
							int.TryParse(list2[4], out var result);
							fileEntity.Size = Math.Ceiling((double)result / 1024.0).ToString();
							list.Add(fileEntity);
						}
					}
				}
			}
			return new Tuple<TransResult, List<FileInfoEntity>>(transResult, list);
		}

		public bool IsFileExist(string fileName, ProgApiResources apiRes)
		{
			return this.RunCommand(new string[1] { "find " + fileName + " -name \"*\"" }).Content.Replace("\n", "") == fileName;
		}

		public TransResult Connect()
		{
			TransResult transResult = new TransResult
			{
				Message = "",
				IsSuccess = true
			};
			try
			{
				if (this._scpClient == null || !this._scpClient.Connected)
				{
					this._scpClient = new Scp(this.Ip, this.User, this.Pwd)
					{
						IsNameFormat = this.IsNameFormat
					};
					IAsyncResult asyncResult = ((Action)delegate
					{
					}).BeginInvoke(null, null);
					asyncResult.AsyncWaitHandle.WaitOne(this.ConTimeOut);
					if (!asyncResult.IsCompleted)
					{
						transResult.Message = "连接超时！";
						transResult.IsSuccess = false;
						return transResult;
					}
					this._scpClient.Connect();
					this._scpClient.OnTransferProgress += this.TransferProgressBar;
					this._scpClient.OnTransferEnd += this.TransferEnd;
				}
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.Message = ex.ToString();
			}
			return transResult;
		}

		public TransResult DownLoadSingle(string localPath, FileInfoEntity dstFileInfo, ProgApiResources apiRes)
		{
			TransResult transResult = new TransResult
			{
				Message = "",
				IsSuccess = true
			};
			try
			{
				transResult = this.Connect();
				this._scpClient.Recursive = false;
				this._scpClient.Put(localPath, dstFileInfo.Path + dstFileInfo.FormatName);
				this.Disconnect();
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.OprType = "上传";
				transResult.TimeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
				transResult.Message = "上传失败:" + ex;
				this.TransErrorHandler?.Invoke(transResult);
			}
			return transResult;
		}

		public TransResult RunCommandScript(string scriptPath)
		{
			return this.RunCommand(new string[1] { CommandHelp.ExcuteScript(scriptPath) });
		}

		public TransResult Rename(string srcFullName, string destFullName)
		{
			string text = "mv " + srcFullName + " " + destFullName;
			return this.RunCommand(new string[1] { text });
		}

		public TransResult RunCommand(string[] commands)
		{
			TransResult transResult = new TransResult
			{
				Message = "",
				IsSuccess = true,
				Content = ""
			};
			if (commands == null || commands.Length == 0)
			{
				transResult.Message = "指令集合为空！";
				transResult.IsSuccess = false;
				return transResult;
			}
			try
			{
				SshExec exec = new SshExec(this.Ip, this.User)
				{
					Password = this.Pwd
				};
				OperateResult<bool> operateResult = TaskManager.StartToDo(delegate
				{
					try
					{
						exec.Connect();
						return true;
					}
					catch (Exception)
					{
						return false;
					}
				}, this.ConTimeOut);
				if (!operateResult.IsSuccess || !operateResult.Content)
				{
					exec.Close();
					exec = null;
					transResult.Message = operateResult.Message;
					transResult.IsSuccess = false;
					return transResult;
				}
				foreach (string text in commands)
				{
					if (text != null && text.Trim().Length != 0)
					{
						string StdErr = "";
						string StdOut = "";
						transResult.IsSuccess = exec.RunCommand(text, ref StdOut, ref StdErr) >= 0;
						transResult.Message = StdErr;
						transResult.Content = StdOut;
					}
				}
				exec.Close();
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.Message = ex.ToString();
			}
			return transResult;
		}

		public Tuple<TransResult, DataTable> GetFileList(string filePath = "/nckfs/_N_MPF_DIR/")
		{
			string text = "find " + filePath + " -name \"*MPF\"";
			DataTable dataTable = new DataTable();
			dataTable.Columns.Add("FileName");
			TransResult transResult = this.RunCommand(new string[1] { text });
			if (!transResult.IsSuccess)
			{
				return new Tuple<TransResult, DataTable>(transResult, dataTable);
			}
			string[] array = transResult.Content.Split('\n');
			string[] array2 = array;
			foreach (string value in array2)
			{
				DataRow dataRow = dataTable.NewRow();
				dataRow["fileName"] = value;
				dataTable.Rows.Add(dataRow);
			}
			return new Tuple<TransResult, DataTable>(transResult, dataTable);
		}

		public TransResult GetModifyFile(int day)
		{
			string[] array = new string[1];
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(47, 1);
			defaultInterpolatedStringHandler.AppendLiteral("find /nckfs/_N_MPF_DIR/ -mtime -");
			defaultInterpolatedStringHandler.AppendFormatted(day);
			defaultInterpolatedStringHandler.AppendLiteral(" -type f -print");
			array[0] = defaultInterpolatedStringHandler.ToStringAndClear();
			return this.RunCommand(array);
		}

		public long GetFileLineCount(string filename)
		{
			string text = "wc -l cw " + filename;
			TransResult transResult = this.RunCommand(new string[1] { text });
			if (transResult.IsSuccess)
			{
				string[] array = transResult.Content.Replace(" ", "").Split('\n');
				if (array.Length != 0 && long.TryParse(array[0].Replace(filename, ""), out var result))
				{
					return result;
				}
			}
			return 0L;
		}

		public TransResult Disconnect()
		{
			TransResult transResult = new TransResult
			{
				Message = "",
				IsSuccess = true
			};
			try
			{
				if (this._scpClient != null && this._scpClient.Connected)
				{
					this._scpClient.Close();
				}
			}
			catch (Exception ex)
			{
				transResult.IsSuccess = false;
				transResult.Message = ex.ToString();
			}
			return transResult;
		}
	}
}
